<template>
  <div class="table_container">
    <div class="fillcontain">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input v-model="listQuery.name" placeholder="食品名称"></el-input>
        </el-col>
        <el-col :span="6">
          <el-select v-model="listQuery.state" placeholder="请选择审核状态">
            <el-option
              v-for="item in stateList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-button type="success" icon="el-icon-search" @click.native="search">{{
            $t('button.search')
          }}</el-button>
          <el-button type="primary" icon="el-icon-refresh" @click.native="reset">{{
            $t('button.reset')
          }}</el-button>
        </el-col>
      </el-row>
      <br />
      <el-table
        :data="tableData"
        @expand="expand"
        :expand-row-keys="expendRow"
        :row-key="(row) => row.index"
        style="width: 100%"
      >
        <el-table-column type="expand">
          <template slot-scope="props">
            <el-form label-position="left" inline class="demo-table-expand">
              <el-form-item label="食品名称">
                <span>{{ props.row.name }}</span>
              </el-form-item>
              <el-form-item label="餐馆名称">
                <span>{{ props.row.shopName }}</span>
              </el-form-item>
              <el-form-item label="食品 ID">
                <span>{{ props.row.item_id }}</span>
              </el-form-item>
              <el-form-item label="餐馆 ID">
                <span>{{ props.row.restaurant_id }}</span>
              </el-form-item>
              <el-form-item label="食品介绍">
                <span>{{ props.row.description }}</span>
              </el-form-item>
              <el-form-item label="餐馆地址">
                <span>{{ props.row.restaurant_address }}</span>
              </el-form-item>
              <el-form-item label="食品评分">
                <span>{{ props.row.rating }}</span>
              </el-form-item>
              <el-form-item label="食品分类">
                <span>{{ props.row.category_id }}</span>
              </el-form-item>
              <el-form-item label="月销量">
                <span>{{ props.row.month_sales }}</span>
              </el-form-item>
              <el-form-item label="审批状态">
                <span>{{ props.row.stateStr }}</span>
              </el-form-item>
              <el-form-item label="审批结果">
                <span>{{ props.row.auditRemark }}</span>
              </el-form-item>
            </el-form>
          </template>
        </el-table-column>
        <el-table-column label="食品名称" prop="name"> </el-table-column>
        <el-table-column label="食品介绍" prop="description"> </el-table-column>
        <el-table-column label="评分" prop="rating"> </el-table-column>
        <el-table-column label="状态" prop="stateStr"> </el-table-column>
        <el-table-column label="操作" width="250">
          <template slot-scope="scope">
            <el-button
              v-if="scope.row.state == '0'"
              size="small"
              type="primary"
              v-permission="['/business/food/audit']"
              @click="handleAudit(scope.row)"
              >审核</el-button
            >
            <el-button
              size="small"
              type="info"
              v-permission="['/business/food/edit']"
              @click="handleEdit(scope.row)"
              >编辑</el-button
            >
            <el-button
              v-if="scope.row.stateStr !== '已删除'"
              size="small"
              type="danger"
              v-permission="['/business/food/delete']"
              @click="handleDelete(scope.$index, scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :page-sizes="[10, 20, 50, 100, 500]"
        :page-size="listQuery.limit"
        :total="total"
        @size-change="changeSize"
        @current-change="fetchPage"
        @prev-click="fetchPrev"
        @next-click="fetchNext"
      >
      </el-pagination>
      <el-dialog title="修改食品信息" :visible.sync="dialogFormVisible">
        <el-form :model="selectTable">
          <el-form-item label="食品名称" label-width="100px">
            <el-input v-model="selectTable.name" auto-complete="off"></el-input>
          </el-form-item>
          <el-form-item label="食品介绍" label-width="100px">
            <el-input v-model="selectTable.description"></el-input>
          </el-form-item>
          <el-form-item label="食品分类" label-width="100px">
            <el-select v-model="selectIndex" :placeholder="selectMenu.label" @change="handleSelect">
              <el-option
                v-for="item in menuOptions"
                :key="item.value"
                :label="item.label"
                :value="item.index"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="食品图片" label-width="100px">
            <el-upload
              class="avatar-uploader"
              :show-file-list="false"
              :action="fileMgrUrl"
              :headers="uploadHeaders"
              :before-upload="handleBeforeUpload"
              :on-success="handleUploadSuccess"
            >
              <img v-if="selectTable.image_path" :src="selectTable.image" class="avatar" />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
        </el-form>
        <el-row style="overflow: auto; text-align: center">
          <el-table :data="specs" style="margin-bottom: 20px" :row-class-name="tableRowClassName">
            <el-table-column prop="specs" label="规格"> </el-table-column>
            <el-table-column prop="packing_fee" label="包装费"> </el-table-column>
            <el-table-column prop="price" label="价格"> </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button size="small" type="danger" @click="deleteSpecs(scope.$index)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
          <el-button type="primary" @click="specsFormVisible = true" style="margin-bottom: 10px"
            >添加规格</el-button
          >
        </el-row>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="updateFood">确 定</el-button>
        </div>
      </el-dialog>

      <el-dialog title="添加规格" :visible.sync="specsFormVisible">
        <el-form :rules="specsFormrules" :model="specsForm">
          <el-form-item label="规格" label-width="100px" prop="specs">
            <el-input v-model="specsForm.specs" auto-complete="off"></el-input>
          </el-form-item>
          <el-form-item label="包装费" label-width="100px">
            <el-input-number v-model="specsForm.packing_fee" :min="0" :max="100"></el-input-number>
          </el-form-item>
          <el-form-item label="价格" label-width="100px">
            <el-input-number v-model="specsForm.price" :min="0" :max="10000"></el-input-number>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="specsFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="addspecs">确 定</el-button>
        </div>
      </el-dialog>

      <el-dialog title="食品审核" :visible.sync="audit.show" width="30%">
        <el-input
          type="textarea"
          :rows="2"
          placeholder="请输入拒绝原因"
          v-model="audit.auditRemark"
        >
        </el-input>
        <span slot="footer" class="dialog-footer">
          <el-button type="danger" @click="handleAuditConfirm(-1)">拒绝</el-button>
          <el-button type="primary" @click="handleAuditConfirm(1)">通过</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getApiUrl } from '@/utils/utils';
import { getToken } from '@/utils/auth';
import permission from '@/directive/permission/index.js';
import { getFoods, updateFood, deleteFood, auditFood } from '@/api/business/food';
import { getResturantDetail, getMenuById, getMenu } from '@/api/business/shop';
import { Loading } from 'element-ui';

export default {
  directives: { permission },
  data() {
    return {
      fileMgrUrl: '',
      uploadHeaders: {
        Authorization: '',
      },
      restaurant_id: null,
      city: {},
      offset: 0,
      limit: 20,
      count: 0,
      tableData: [],
      currentPage: 1,
      selectTable: {},
      dialogFormVisible: false,
      menuOptions: [],
      selectMenu: {},
      selectIndex: null,
      specsForm: {
        specs: '',
        packing_fee: 0,
        price: 20,
      },
      specsFormrules: {
        specs: [{ required: true, message: '请输入规格', trigger: 'blur' }],
      },
      specsFormVisible: false,
      expendRow: [],
      total: 0,
      stateList: [
        { label: '审核中', value: '0' },
        { label: '审核通过', value: '1' },
        { label: '审核拒绝', value: '-1' },
      ],
      audit: { show: false, auditRemark: '' },
      listQuery: {
        page: 1,
        limit: 20,
        name: '',
        state: '',
      },
    };
  },
  created() {
    this.restaurant_id = this.$route.query.restaurant_id;
    this.initData();
    this.fileMgrUrl = getApiUrl() + '/file';
    this.uploadHeaders['Authorization'] = getToken();
  },
  computed: {
    specs: function () {
      let specs = [];
      if (this.selectTable.specfoods) {
        this.selectTable.specfoods.forEach((item) => {
          specs.push({
            specs: item.specs_name,
            packing_fee: item.packing_fee,
            price: item.price,
          });
        });
      }
      return specs;
    },
  },
  methods: {
    search() {
      this.fetchData();
    },
    reset() {
      this.listQuery.state = '';
      this.listQuery.name = '';
      this.fetchData();
    },
    async initData() {
      this.fetchData();
    },
    async getMenu() {
      this.menuOptions = [];
      try {
        const menuResponse = await getMenu({
          restaurant_id: this.selectTable.restaurant_id,
          allMenu: true,
        });
        const menu = menuResponse.data;
        menu.forEach((item, index) => {
          this.menuOptions.push({
            label: item.name,
            value: item.id,
            index,
          });
        });
      } catch (err) {
        console.log('获取食品种类失败', err);
      }
    },
    async fetchData() {
      getFoods({
        page: this.listQuery.page,
        limit: this.listQuery.limit,
        state: this.listQuery.state,
        name: this.listQuery.name,
        restaurant_id: this.restaurant_id,
      }).then((response) => {
        this.tableData = [];
        const foods = response.data.records;
        this.total = response.data.total;
        foods.forEach((item, index) => {
          const tableData = {};
          tableData.name = item.name;
          tableData.item_id = item.item_id;
          tableData.description = item.description;
          tableData.rating = item.rating;
          tableData.month_sales = item.month_sales;
          tableData.restaurant_id = item.restaurant_id;
          tableData.category_id = item.category_id;
          tableData.image_path = item.image_path;
          tableData.specfoods = item.specfoods;
          tableData.index = index;
          tableData.state = item.state;
          tableData.stateStr = item.stateStr;
          tableData.auditRemark = item.auditRemark;
          tableData.shopName = item.shopName;
          this.tableData.push(tableData);
        });
      });
    },
    tableRowClassName(row, index) {
      if (index === 1) {
        return 'info-row';
      } else if (index === 3) {
        return 'positive-row';
      }
      return '';
    },
    addspecs() {
      this.specs.push({ ...this.specsForm });
      this.specsForm.specs = '';
      this.specsForm.packing_fee = 0;
      this.specsForm.price = 20;
      this.specsFormVisible = false;
    },
    deleteSpecs(index) {
      this.specs.splice(index, 1);
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.offset = (val - 1) * this.limit;
      this.fetchData();
    },
    expand(row, status) {
      if (status) {
        this.getSelectItemData(row);
      } else {
        const index = this.expendRow.indexOf(row.index);
        this.expendRow.splice(index, 1);
      }
    },
    handleAudit(row) {
      this.audit.show = true;
      this.selectTable = row;
    },
    handleAuditConfirm(state) {
      if (state == '-1') {
        if (this.audit.auditRemark == '') {
          this.$message({
            type: 'warning',
            message: '请输入拒绝原因',
          });
          return;
        }
      }
      const params = {
        item_id: this.selectTable.item_id,
        state: state,
        auditRemark: this.audit.auditRemark,
      };

      auditFood(params).then(() => {
        this.$message({
          type: 'success',
          message: '审核成功',
        });
        this.fetchData();
      });
      this.audit.show = false;
    },
    handleEdit(row) {
      this.getSelectItemData(row, 'edit');
      this.dialogFormVisible = true;
    },
    async getSelectItemData(row, type) {
      const response = await getResturantDetail(row.restaurant_id);
      const restaurant = response.data;
      const categoryResponse = await getMenuById(row.category_id);
      const category = categoryResponse.data;
      this.selectTable = {
        ...row,
        ...{
          restaurant_name: restaurant.name,
          restaurant_address: restaurant.address,
          category_name: category.name,
          image: getApiUrl() + '/file/getImgStream?fileName=' + row.image_path,
        },
      };

      this.selectMenu = { label: category.name, value: row.category_id };
      this.tableData.splice(row.index, 1, { ...this.selectTable });
      this.$nextTick(() => {
        this.expendRow.push(row.index);
      });
      if (type === 'edit' && this.restaurant_id !== row.restaurant_id) {
        this.getMenu();
      }
    },
    handleSelect(index) {
      this.selectIndex = index;
      this.selectMenu = this.menuOptions[index];
    },
    async handleDelete(index, row) {
      try {
        deleteFood(row.item_id).then(() => {
          this.$message({
            type: 'success',
            message: '删除食品成功',
          });
          this.tableData.splice(index, 1);
        });
      } catch (err) {
        this.$message({
          type: 'error',
          message: err.message,
        });
        console.log('删除食品失败');
      }
    },
    handleServiceAvatarScucess(res) {
      if (res.status === 1) {
        this.selectTable.image_path = res.image_path;
      } else {
        this.$message.error('上传图片失败！');
      }
    },
    beforeAvatarUpload(file) {
      const isRightType = file.type === 'image/jpeg' || file.type === 'image/png';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isRightType) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isRightType && isLt2M;
    },

    handleBeforeUpload() {
      this.loadingInstance = Loading.service({
        lock: true,
        text: this.$t('common.uploading'),
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)',
      });
    },
    handleUploadSuccess(response) {
      this.loadingInstance.close();
      if (response.code === 20000) {
        console.log(response.data);
        this.selectTable.image_path = response.data.realFileName;
        this.selectTable.image =
          getApiUrl() + '/file/getImgStream?fileName=' + response.data.realFileName;
      } else {
        this.$message({
          message: this.$t('common.uploadError'),
          type: 'error',
        });
      }
    },
    async updateFood() {
      this.dialogFormVisible = false;

      // const subData = { new_category_id: this.selectMenu.value, specs: this.specs }
      // const postData = { ...this.selectTable, ...subData }

      const me = this;
      updateFood({
        name: me.selectTable.name,
        id: me.selectTable.item_id,
        descript: me.selectTable.description,
        idMenu: me.selectMenu.value,
        idShop: me.selectTable.restaurant_id,
        imagePath: me.selectTable.image_path,
        specsJson: JSON.stringify(me.specs),
      })
        .then(() => {
          this.fetchData();
          this.$message({
            type: 'success',
            message: '更新食品信息成功',
          });
        })
        .catch((err) => {
          this.$message({
            type: 'error',
            message: err.message,
          });
        });
    },
    fetchNext() {
      this.listQuery.page = this.listQuery.page + 1;
      this.fetchData();
    },
    fetchPrev() {
      this.listQuery.page = this.listQuery.page - 1;
      this.fetchData();
    },
    fetchPage(page) {
      this.listQuery.page = page;
      this.fetchData();
    },
    changeSize(limit) {
      this.listQuery.limit = limit;
      this.fetchData();
    },
  },
};
</script>

<style lang="scss">
.demo-table-expand {
  font-size: 0;
}
.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}
.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}
.table_container {
  padding: 20px;
}
.Pagination {
  display: flex;
  justify-content: flex-start;
  margin-top: 8px;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #20a0ff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}
.avatar {
  width: 120px;
  height: 120px;
  display: block;
}
</style>
